<?php

namespace App\Models\Elasticsearch\Settlement;

use App\Models\Elasticsearch\Model;

class Info extends Model
{

    const INDEX_NAME = 't_settlement_info';

    /**
     * 玩家类型【玩家】
     */
    const PLAYER_TYPE = 1;

    /**
     * 玩家类型【AI】
     */
    const PLAYER_TYPE_AI = 2;

    /**
     * 状态【正常】
     */
    const STATUS_NORMAL = 1;

    /**
     * 状态【挂起】
     */
    const STATUS_ABNORMAL = 2;

    /**
     * 获取去重统计字段列表
     *
     * @param int $timeStart
     * @param int $timeEnd
     * @param array $fields
     * @return \Illuminate\Support\Collection
     * @throws \Exception
     */
    protected function getStatsDistinct(int $timeStart, int $timeEnd, array $fields)
    {
        $params = ['body' => ['size' => 0, 'track_total_hits' => false]];
        // 时间筛选
        $params['body']['query']['bool']['must'][] = [
            'range' => [
                'end_time' => ['gte' => $timeStart, 'lt' => $timeEnd]
            ]
        ];
        // 统计字段
        $params['body']['aggs'] = [
            'group' => [
                'composite' => [
                    'size' => $size = config('elasticsearch.search.max_buckets'),
                    'sources' => array_map(function ($field) {
                        return [$field => ['terms' => ['field' => $field]]];
                    }, $fields)
                ]
            ]
        ];
        // 查询数据
        $results = $this->search($params);

        // 数量检查
        if (count($results['aggregations']['group']['buckets']) >= $size) {
            throw new \Exception("字段去重数量已达到 {$size} 条，请调整统计拆分规则");
        }

        return collect(
            array_column($results['aggregations']['group']['buckets'], 'key')
        );
    }
}
